<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <TransitionGroup name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index + item.path">
        <span v-if="index == breadcrumbList.length - 1" class="no-redirect">{{ item.meta?.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta?.title }}</a>
      </el-breadcrumb-item>
    </TransitionGroup>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import type { RouteRecordRaw } from 'vue-router'
const route = useRoute()
const router = useRouter()
let breadcrumbList = ref<RouteRecordRaw[]>([])

function getBreadcrumb() {
  // only show routes with meta.title
  let matched: RouteRecordRaw[] = route.matched.filter(item => item.meta && item.meta.title)
  const first = matched[0]
  if (!isDashboard(first)) {
    const firstList: RouteRecordRaw[] = [{ path: '/search', component: () => import('@/views/Search/UserSearch/index.vue'), meta: { title: '首页' } }]
    matched = firstList.concat(matched)
  }
  breadcrumbList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
}

function isDashboard(route: RouteRecordRaw) {
  const name = route && (route.name as string)
  if (!name) return false
  return name.trim() === 'Search'
}

function handleLink(route: RouteRecordRaw) {
  router.push(route.path)
}

watch(route, () => getBreadcrumb(), { immediate: true })
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  position: relative;
  display: inline-block;
  font-size: 14px;
  margin-left: 8px;
  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
